import React, { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { Card, Row, Col, Input, Select, Button, Space, Spin, Empty, Pagination } from 'antd';
import { SearchOutlined, FilterOutlined } from '@ant-design/icons';
import { useQuery } from '@tanstack/react-query';
import { getCourseList, getCourseCategories } from '../api/divide/course/sdk.gen';
import CourseCard from '../components/CourseCard';

const { Search } = Input;
const { Option } = Select;

const Courses: React.FC = () => {
  const navigate = useNavigate();
  const [searchText, setSearchText] = useState('');
  const [selectedLevel, setSelectedLevel] = useState<string>('');
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(12);

  // 获取课程分类
  const { data: categoriesData } = useQuery({
    queryKey: ['courseCategories'],
    queryFn: () => getCourseCategories(),
  });

  // 获取课程列表
  const { data: coursesData, isLoading, refetch } = useQuery({
    queryKey: ['courses', currentPage, pageSize, searchText, selectedLevel],
    queryFn: () => getCourseList({
      query: {
        page: currentPage,
        size: pageSize,
      }
    }),
  });

  const courses = coursesData?.data?.data?.records || [];
  const total = coursesData?.data?.data?.total || 0;
  const categories = categoriesData?.data?.data || [];

  const handleSearch = () => {
    setCurrentPage(1);
    refetch();
  };

  const handleReset = () => {
    setSearchText('');
    setSelectedLevel('');
    setCurrentPage(1);
  };

  return (
    <div style={{ padding:'540px 24px 24px 0' }}>
      <Card style={{ marginBottom: 24 }}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div>
            <h1 style={{ marginBottom: 16 }}>课程列表</h1>
            <p style={{ color: '#666' }}>探索我们精心设计的Redis学习课程</p>
          </div>

          <Space wrap style={{ width: '100%' }}>
            <Search
              placeholder="搜索课程名称或描述"
              allowClear
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              onSearch={handleSearch}
              style={{ width: 300 }}
              prefix={<SearchOutlined />}
            />
            
            <Select
              placeholder="选择难度等级"
              allowClear
              value={selectedLevel}
              onChange={setSelectedLevel}
              style={{ width: 150 }}
            >
              {Array.isArray(categories) && categories.map((category, index) => {
                const key = Object.keys(category)[0];
                const value = category[key];
                return (
                  <Option key={`${key}-${index}`} value={key}>
                    {value}
                  </Option>
                );
              })}
            </Select>

            <Button type="primary" onClick={handleSearch} icon={<SearchOutlined />}>
              搜索
            </Button>
            
            <Button onClick={handleReset} icon={<FilterOutlined />}>
              重置
            </Button>
          </Space>
        </Space>
      </Card>

      <Spin spinning={isLoading}>
        {courses.length > 0 ? (
            <>
              <Row gutter={[24, 24]}>
                {courses.map((course) => (
                    <Col key={course.id} xs={24} sm={12} md={8} lg={6} xl={6}>
                      <CourseCard
                          course={course}
                          onCardClick={() => navigate(`/courses/${course.id}`)}
                          onAddToCart={(course) => {
                            // TODO: 添加到购物车逻辑
                            console.log('添加到购物车:', course);
                          }}
                          onToggleFavorite={(course) => {
                            // TODO: 收藏课程逻辑
                            console.log('切换收藏:', course);
                          }}
                      />
                    </Col>
                ))}
              </Row>

              <div style={{
                marginTop: 24,
                display: 'flex',
                justifyContent: 'center',
                alignItems: 'center'
              }}>
                <Pagination
                    current={currentPage}
                    total={total}
                    pageSize={pageSize}
                    onChange={setCurrentPage}
                    showSizeChanger={false}
                    showTotal={(total) => `共 ${total} 条记录`}
                />
              </div>
            </>
        ) : (
            <Empty
                description="暂无课程数据"
                style={{marginTop: 100}}
            />
        )}
      </Spin>
    </div>
  );
};

export default Courses;